﻿using System;
using System.Collections.Generic;
using System.Threading;
using Duo1JHttpServer.Framework.Analyzer;
using Duo1JHttpServer.Framework.Config;
using Duo1JHttpServer.Framework.Server;
using Duo1JHttpServer.Framework.Utils;

namespace Duo1JHttpServer
{
    public class WebMain
    {
        /// <summary>
        /// 运行中标志量
        /// </summary>
        internal static volatile bool running = true;

        /// <summary>
        /// 服务器实例
        /// </summary>
        private static WebServer webServer;

        private static void Main(string[] args)
        {
            Start();
        }

        /// <summary>
        /// 启动服务器
        /// </summary>
        public static void Start()
        {
            try
            {
                PrintIcon();
                InitStatic();
                InitConfig();

                ConfigManager.ServerProperties.TryGetValue(ConfigDefine.Server_IPAddress, out string ipAddress);
                ConfigManager.ServerProperties.TryGetValue(ConfigDefine.Server_Port, out string port);
                webServer = new WebServer(ipAddress ?? "127.0.0.1", port == null ? 8080 : Convert.ToInt32(port));

                new Thread(webServer.Listen).Start();
                new Thread(new ConsoleHandler().InputHandler).Start();
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                Close();
            }
        }

        /// <summary>
        /// 打印字符画icon
        /// </summary>
        private static void PrintIcon()
        {
            byte[] icon = IOUtils.ReadFileAll(GlobalDefine.StaticRoot + "icon.txt");
            if (icon != null)
            {
                ConsoleUtils.WriteBlueLine(System.Text.Encoding.UTF8.GetString(icon));
            }
        }

        /// <summary>
        /// 初始化静态类
        /// </summary>
        private static void InitStatic()
        {
            ConsoleUtils.WriteGreenLine(">InitStatic");
            ConfigManager.StartUp();
        }

        /// <summary>
        /// 初始化配置
        /// </summary>
        private static void InitConfig()
        {
            ConsoleUtils.WriteGreenLine(">InitConfig");
            ConfigAnalyzer.AnalyzeConfig();
        }

        /// <summary>
        /// 关闭服务器
        /// </summary>
        public static void Close()
        {
            ConsoleUtils.WriteRedLine("Close Server..");
            running = false;
            webServer.Close();
        }
    }
}